package cn.parus.dynamicRouter.metrics;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.stereotype.Component;

/**
 * @Title: GatewayMetrics
 * @Author 黄莲娇
 * @Package com.status.dynamicRouter.metrics
 * @Date 2024/4/4 13:51
 * @description: 网关指标收集服务，用于记录请求数量、响应时间和状态码等监控指标
 * @Version: 1.0
 */

@Component
public class GatewayMetrics {
    private final MeterRegistry registry;

    public GatewayMetrics(MeterRegistry registry) {
        this.registry = registry;
    }

    // 记录请求的方法
    public void recordRequest(String routeId) {
        Counter.builder("gateway_requests_total")
                .tag("route_id", routeId)
                .description("Total number of requests")
                .register(registry)
                .increment();
    }

    // 开始计时
    public Timer.Sample startTimer() {
        return Timer.start(registry);
    }

    // 停止计时并记录
    public void stopTimer(Timer.Sample sample, String routeId) {
        Timer timer = Timer.builder("gateway_duration_seconds")
                .tag("route_id", routeId)
                .description("Request duration in seconds")
                .register(registry);
        sample.stop(timer);
    }

    // 记录状态码
    public void recordStatus(String routeId, String status) {
        Counter.builder("gateway_status_total")
                .tag("route_id", routeId)
                .tag("status", status)
                .description("Total number of requests by status code")
                .register(registry)
                .increment();
    }
}
